package com.yao.mylock.service;

import com.yao.mylock.entity.Stock1;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Macrydy
 * @date 2022/9/5
 */
@Service
public class StockService1 {
    private Stock1 stock = new Stock1();

    private ReentrantLock lock = new ReentrantLock();

    //减库存 方法一：使用synchronized
    public synchronized void deduct() {

        stock.setStock(stock.getStock() - 1);
        System.out.println("当前库存余量为：" + stock.getStock());
    }

    //减库存 方法二：使用ReentrantLock
    public void deduct1() {

        try {
            stock.setStock(stock.getStock() - 1);
            System.out.println("当前库存余量为：" + stock.getStock());
        } finally {
            lock.unlock();
        }
    }
}
